#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

from app import app, lm, db, csrf
from module.tableclass import Admin, StuInfo, Computer, Reservation, Log, Statistics
from flask import render_template, flash, redirect, request, url_for, g, session
from module.login import AdminLoginForm
from flask_login import login_user, current_user, login_required, logout_user
from flask_wtf import Form
import json
import time
from datetime import date, timedelta

@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
	#预约界面
	form = Form()
	if request.method == 'POST':
		StuID = request.form['StuID']
		Password = request.form['Password']
		student = StuInfo.query.get(StuID)
		if student is None or  student.Password != Password:
			flash("学号或者密码错误！")
			return render_template('index.html', form = form)
		else:
			tomorrow = date.today() + timedelta(1)
			ret = Reservation.query.filter_by(StuID = student.StuID, ResDate = str(tomorrow)).all()
			if len(ret) > 0:
				flash("已经预约！")
				return render_template('index.html', form = form)
			ret = Reservation.query.filter(Reservation.StuID == student.StuID, Reservation.isDone == 'N').all()
			if len(ret) > 2:
				flash("多次预约，没有上机，请联系管理员！")
				return render_template('index.html', form = form)
			ret = Computer.query.filter_by(isReady = 'Y', isBreakdown = 'N').all()
			if len(ret) == 0:
				flash("无可用机器！")
				return render_template('index.html', form = form)
			computer = {}
			reservation = Reservation()
			reservation.StuID = student.StuID
			reservation.ResDate = str(tomorrow)
			reservation.isDone = 'N'
			reservation.ComputerID = ret[0].ComputerID
			reservation.RoomID = ret[0].RoomID
			reservation.StartTime = None
			reservation.FinishTime = None
			db.session.add(reservation)
			computer['ComputerID'] = ret[0].ComputerID
			computer['RoomID'] = ret[0].RoomID
			ret[0].isReady = 'N'
			log = Log()
			log.StuID = student.StuID
			log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
			log.Action = "预约机器"
			db.session.add(log)
			db.session.commit()
			return render_template('index.html', form = form, computer = computer)
	else:
		return render_template('index.html', form = form)

@app.route('/StuInfo',methods=['POST'])
@csrf.exempt
def postStuInfo():
	#与传输机通讯接口
	stuID = request.form['ID']

	result= {}
	cueentDate = time.strftime('%Y-%m-%d',time.localtime(time.time()))

	stuInfo = StuInfo.query.get(stuID)
	if stuInfo is None:
		#未找到该同学
		result = {
			'isValid':False,
			'errormsg':"Invalid ID!"
		}
	else:
		ResDate = Reservation.query.get((stuID, cueentDate,))
		if ResDate is None:
			#没有预约
			result = {
				'isValid':False,
				'errormsg':"Not make reservation!"
			}
		else:
			if ResDate.isDone == 'Y':
				#预约，并已经上机
				result = {
					'isValid':False,
					'errormsg':"Reservation has been done!"
				}
			else:
				computer = Computer.query.get((ResDate.ComputerID, ResDate.RoomID,))
				if ResDate.StartTime is None:
					ResDate.StartTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
					log = Log()
					log.StuID = stuInfo.StuID
					log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
					log.Action = "上机"
					db.session.commit()
					result = {
						'isValid':True,
						'Time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),
						'StuInfo':{
							"StuID":str(stuInfo.StuID),
							"Name":str(stuInfo.Name),
							"Date":str(stuInfo.Date)
						},
						"Computer":{
							'ComputerID':int(computer.ComputerID),
							'RoomID':str(computer.RoomID),
							'Password':str(computer.Password)
						}
					}
				else:
					ResDate.FinishTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
					ResDate.isDone = 'Y'
					computer.isReady = 'Y'
					log = Log()
					log.StuID = stuInfo.StuID
					log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
					log.Action = "下机"
					db.session.add(log)
					db.session.commit()
					result = {
						'isValid':False,
						'errormsg':"OK"
					}
	return json.dumps(result)

@app.route('/admin', methods = ['GET'])
@app.route('/admin/stuinfo')
@login_required
def stuinfo_list():
	#学生管理
	page = request.args.get('page')
	if page is None:
		page = 1
	else:
		page = int(page)
	students = StuInfo.query.order_by('StuID').offset((page-1)*30).limit(30).all()
	return render_template('student_list.html', title = '学生管理', students = students)

@app.route('/admin/stuinfo/add', methods = ['GET', 'POST'])
@login_required
def stuinfo_add():
	if request.method == 'POST':
		print json.dumps(request.form)
		student = StuInfo()
		student.StuID = request.form['StuID']
		student.Password = request.form['Password']
		student.Name = request.form['Name']
		student.Gender = request.form['Gender']
		student.Class = request.form['Class']
		student.Dormitory = request.form['Dormitory']
		student.Phone = request.form['Phone']
		student.Date = request.form['Date']
		db.session.add(student)
		db.session.commit()
		flash("添加成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "添加学生信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/stuinfo')
	else:
		form = Form()
		return render_template('student_add.html', title = '添加学生信息', form = form)


@app.route('/admin/stuinfo/alter', methods = ['GET', 'POST'])
@login_required
def stuinfo_alter():
	if request.method == 'POST':
		student = StuInfo.query.get(request.form['StuID'])
		student.Password = request.form['Password']
		student.Name = request.form['Name']
		student.Gender = request.form['Gender']
		student.Class = request.form['Class']
		student.Dormitory = request.form['Dormitory']
		student.Phone = request.form['Phone']
		student.Date = request.form['Date']
		db.session.commit()
		flash("修改成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "修改学生信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/stuinfo')
	else:
		form = Form()
		StuID = request.args.get('StuID')
		if StuID is None:
			return redirect('/admin/stuinfo')
		student = StuInfo.query.get(StuID)
		if student is None:
			return redirect('/admin/stuinfo')
		return render_template('student_alter.html', title = '修改学生信息', student = student, form = form)

@app.route('/admin/stuinfo/delete')
@login_required
def stuinfo_delete():
	StuID = request.args.get('StuID')
	if StuID is None:
		return redirect('/admin/stuinfo')
	student = StuInfo.query.get(StuID)
	if student is None:
		return redirect('/admin/stuinfo')
	db.session.delete(student)
	db.session.commit()
	flash("删除成功！")
	log = Log()
	log.StuID = g.user.AdminID
	log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
	log.Action = "删除学生信息"
	db.session.add(log)
	db.session.commit()
	return redirect('/admin/stuinfo')

@app.route('/admin/reservation')
@login_required
def reservation_list():
	#预约管理
	page = request.args.get('page')
	if page is None:
		page = 1
	else:
		page = int(page)
	reservations = Reservation.query.order_by('StuID', 'ResDate').offset((page-1)*30).limit(30).all()
	return render_template('reservation_list.html', title = '预约管理', reservations = reservations)

@app.route('/admin/reservation/add', methods = ['GET', 'POST'])
@login_required
def reservation_add():
	if request.method == 'POST':
		print request.form
		reservation = Reservation()
		reservation.StuID = request.form['StuID']
		reservation.ResDate = request.form['ResDate']
		reservation.isDone = request.form['isDone']
		reservation.ComputerID = request.form['ComputerID']
		reservation.RoomID = request.form['RoomID']
		reservation.StartTime = None
		reservation.FinishTime = None
		db.session.add(reservation)
		db.session.commit()
		flash("添加成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "添加预约信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/reservation')
	else:
		form = Form()
		return render_template('reservation_add.html', title = '添加预约信息', form = form)


@app.route('/admin/reservation/alter', methods = ['GET', 'POST'])
@login_required
def reservation_alter():
	if request.method == 'POST':
		reservation = Reservation.query.get((request.form['StuID'],
											request.form['ResDate'],)
		)
		reservation.isDone = request.form['isDone']
		reservation.ComputerID = request.form['ComputerID']
		reservation.RoomID = request.form['RoomID']
		db.session.commit()
		flash("修改成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "修改预约信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/reservation')
	else:
		form = Form()
		StuID = request.args.get('StuID')
		ResDate = request.args.get('ResDate')
		if StuID is None or ResDate is None:
			return redirect('/admin/reservation')
		reservation = Reservation.query.get((StuID, ResDate,))
		if reservation is None:
			return redirect('/admin/reservation')
		return render_template('reservation_alter.html', title = '修改预约信息', reservation = reservation, form = form)

@app.route('/admin/reservation/delete')
@login_required
def reservation_delete():
	StuID = request.args.get('StuID')
	ResDate = request.args.get('ResDate')
	if StuID is None or ResDate is None:
		return redirect('/admin/reservation')
	reservation = Reservation.query.get((StuID, ResDate,))
	if reservation is None:
		return redirect('/admin/reservation')
	db.session.delete(reservation)
	db.session.commit()
	flash("删除成功！")
	log = Log()
	log.StuID = g.user.AdminID
	log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
	log.Action = "删除预约信息"
	db.session.add(log)
	db.session.commit()
	return redirect('/admin/reservation')

@app.route('/admin/computer')
@login_required
def computer_list():
	#机器管理
	page = request.args.get('page')
	if page is None:
		page = 1
	else:
		page = int(page)
	computers = Computer.query.order_by('RoomID', 'ComputerID').offset((page-1)*30).limit(30).all()
	return render_template('computer_list.html', title = '机器管理', computers = computers)

@app.route('/admin/computer/add', methods = ['GET', 'POST'])
@login_required
def computer_add():
	if request.method == 'POST':
		computer = Computer()
		computer.ComputerID = request.form['ComputerID']
		computer.RoomID = request.form['RoomID']
		computer.Password = request.form['Password']
		computer.isReady = request.form['isReady']
		computer.isBreakdown = request.form['isBreakdown']
		db.session.add(computer)
		db.session.commit()
		flash("添加成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "添加机器信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/computer')
	else:
		form = Form()
		return render_template('computer_add.html', title = '添加机器信息', form = form)


@app.route('/admin/computer/alter', methods = ['GET', 'POST'])
@login_required
def computer_alter():
	if request.method == 'POST':
		computer = Computer.query.get((request.form['ComputerID'], request.form['RoomID'],))
		computer.Password = request.form['Password']
		computer.isReady = request.form['isReady']
		computer.isBreakdown = request.form['isBreakdown']
		db.session.commit()
		flash("修改成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "修改机器信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/computer')
	else:
		form = Form()
		ComputerID = request.args.get('ComputerID')
		RoomID = request.args.get('RoomID')
		if ComputerID is None or RoomID is None:
			return redirect('/admin/computer')
		computer = Computer.query.get((ComputerID, RoomID,))
		if computer is None:
			return redirect('/admin/computer')
		return render_template('computer_alter.html', title = '修改机器信息', computer = computer, form = form)

@app.route('/admin/computer/delete')
@login_required
def computer_delete():
	ComputerID = request.args.get('ComputerID')
	RoomID = request.args.get('RoomID')
	if ComputerID is None or RoomID is None:
		return redirect('/admin/computer')
	computer = Computer.query.get((ComputerID, RoomID,))
	if computer is None:
		return redirect('/admin/computer')
	db.session.delete(computer)
	db.session.commit()
	flash("删除成功！")
	log = Log()
	log.StuID = g.user.AdminID
	log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
	log.Action = "删除机器信息"
	db.session.add(log)
	db.session.commit()
	return redirect('/admin/computer')

@app.route('/admin/admin')
@login_required
def admin_list():
	#管理员管理
	page = request.args.get('page')
	if page is None:
		page = 1
	else:
		page = int(page)
	admins = Admin.query.order_by('AdminID').offset((page-1)*30).limit(30).all()
	print admins
	return render_template('admin_list.html', title = '管理员管理', admins = admins)

@app.route('/admin/admin/add', methods = ['GET', 'POST'])
@login_required
def admin_add():
	if request.method == 'POST':
		admin = Admin()
		admin.AdminID = request.form['AdminID']
		admin.Name = request.form['Name']
		admin.Password = request.form['Password']
		print admin
		db.session.add(admin)
		db.session.commit()
		flash("添加成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "添加管理员信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/admin')
	else:
		form = Form()
		return render_template('admin_add.html', title = '添加管理员', form = form)

@app.route('/admin/admin/alter', methods = ['GET', 'POST'])
@login_required
def admin_alter():
	if request.method == 'POST':
		admin = Admin.query.get(request.form['id'])
		admin.name = request.form['name']
		db.session.commit()
		flash("修改成功！")
		log = Log()
		log.StuID = g.user.AdminID
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "修改管理员信息"
		db.session.add(log)
		db.session.commit()
		return redirect('/admin/admin')
	else:
		form = Form()
		ID = request.args.get('id')
		if ID is None:
			return redirect('/admin/admin')
		admin = Admin.query.get(ID)
		if admin is None:
			return redirect('/admin/admin')
		return render_template('admin_alter.html', title = '修改管理员信息', admin = admin, form = form)

@app.route('/admin/admin/delete')
@login_required
def admin_delete():
	ID = request.args.get('id')
	if ID is None:
		return redirect('/admin/admin')
	admin = Admin.query.get(ID)
	if admin is None:
		return redirect('/admin/admin')
	db.session.delete(admin)
	db.session.commit()
	flash("删除成功！")
	log = Log()
	log.StuID = g.user.AdminID
	log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
	log.Action = "删除管理员信息"
	db.session.add(log)
	db.session.commit()
	return redirect('/admin/admin')

@app.route('/admin/statistics', methods = ['GET', 'POST'])
@app.route('/admin/statistics/student', methods = ['GET', 'POST'])
@login_required
def statistics_student():
	#统计列表
	form = Form()
	students = StuInfo.query.all()
	stat_stus = []
	for student in students:
		Times = None
		if request.method == 'GET':
			reservations = Reservation.query.filter(Reservation.StuID == student.StuID)
		else:
			BeginDate = request.form['BeginDate']
			EndDate = request.form['EndDate']
			Times = request.form['Times']
			reservations = Reservation.query.filter(Reservation.StuID == student.StuID, 
													Reservation.ResDate >= BeginDate,
													Reservation.ResDate <= EndDate
												)
		count_all = len(reservations.all())
		count = len(reservations.filter(Reservation.isDone == 'Y').all())
		stat_stu = Statistics()
		stat_stu.StuID = student.StuID
		stat_stu.Name = student.Name
		stat_stu.Class = student.Class
		stat_stu.Count = count
		stat_stu.All = count_all
		if count_all == 0:
			stat_stu.Percent = 100
		else:
			stat_stu.Percent = int(count*1.0/count_all * 100)
		if Times is not None:
			if count_all - count >= int(Times):
				stat_stus.append(stat_stu)
		else:
			stat_stus.append(stat_stu)
	return render_template('statistics_stulist.html', title = '学生统计', stat_stus = stat_stus, form = form)

@app.route('/admin/statistics/class')
@login_required
def statistics_class():
	#统计列表
	class_list = db.session.query(StuInfo.Class).distinct().all()
	stat_class = []
	for class_item in class_list:
		count = 0
		count_all = 0
		students = StuInfo.query.filter(StuInfo.Class == class_item[0]).all()
		print students
		for student in students:
			reservations = Reservation.query.filter(Reservation.StuID == student.StuID)
			count_all += len(reservations.all())
			count += len(reservations.filter(Reservation.isDone == 'Y').all())
		stat = Statistics()
		stat.Class = class_item[0]
		stat.Count = count
		stat.All = count_all
		if count_all == 0:
			stat.Percent = 100
		else:
			stat.Percent = int(count*1.0/count_all * 100)
		stat_class.append(stat)
		print stat, stat.Class, stat.Count, stat.All, stat.Percent
	return render_template('statistics_classlist.html', title = '班级统计', stat_classes = stat_class)

@app.route('/admin/log')
@login_required
def log_list():
	#日志列表
	page = request.args.get('page')
	if page is None:
		page = 1
	else:
		page = int(page)
	logs = Log.query.order_by(db.desc('Time')).offset((page-1)*30).limit(30).all()
	return render_template('log_list.html', title = '操作日志', logs = logs)

@app.route('/login', methods = ['GET', 'POST'])
def login():
	form = AdminLoginForm()
	if request.method == 'POST' and form.validate_on_submit():
		username = form.username.data
		password = form.password.data
		session['remember_me'] = form.remember_me.data
		user = Admin.query.get(username)
		if user is None or user.Password != password:
			flash("登陆失败，请确认用户名密码！")
			log = Log()
			log.StuID = username
			log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
			log.Action = "尝试登陆，失败！"
			db.session.add(log)
			db.session.commit()
			return render_template('login.html', title = '登陆', form = form)
		g.user = user
		login_user(user, remember = form.remember_me.data)
		next = request.args.get('next')
		log = Log()
		log.StuID = username
		log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		log.Action = "登陆成功！"
		db.session.add(log)
		db.session.commit()
		return redirect(next or '/admin')
	else:
		return render_template('login.html', title = '登陆', form = form)

@app.route('/logout')
def logout():
	#推出登陆
	log = Log()
	log.StuID = g.user.AdminID
	log.Time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
	log.Action = "退出登陆"
	db.session.add(log)
	db.session.commit()
	logout_user()
	return redirect('/login')

@app.route('/test')
def test():
	#临时测试功能
	user = Reservation.query.filter(Reservation.StuID == '913106840350', Reservation.ResDate != '2016-09-30', ).all()
	print user
	return "ok"

@lm.user_loader
def user_loader(user_id):
	#用户载入回调函数
	return Admin.query.get(user_id)

@app.before_request
def before_request():
	#请求前动作
	g.user = current_user
